'use strict';
const { ERROR_CODE,STATUS,HTTP_STATUS } = require('./code')


function getCode (num,df=0){
  if (typeof num !== 'number') throw new Error(`err code must be number, but get : ${num} `)
  if (typeof df !== 'number')  throw new Error(`err default code must be number, but get : ${df} `)
  // wx: errcode : >1w+
  if (df<0  || df>999)         throw new Error(`err default code must be 0~999, but get : ${df} `)
  return num + df
}

// 系统常规错误
const CUSTOM_ERROR = 0
class CustomError extends Error {
  CODE = CUSTOM_ERROR
  constructor(message, code = 0) {
    super(message);
    this.name = 'CustomError'
    this.code = getCode(this.CODE, code)
  }
}
CustomError.CODE = CUSTOM_ERROR

// 系统向外请求错误
const HTTP_ERROR = 1000
class HttpError extends Error {
  CODE = HTTP_ERROR
  constructor(message, code=0) {
    super(message);
    this.name = 'HttpError'
    this.code = code > 9999 ? code : getCode(this.CODE, code)
  }
}
HttpError.CODE = HTTP_ERROR

// 系统数据库操作相关错误
const DB_ERROR = 2000
class DbError extends Error {
  CODE = DB_ERROR
  constructor(message, code=0) {
    super(message);
    this.name = 'DbError'
    this.code = getCode(this.CODE, code)
  }
}
DbError.CODE = DB_ERROR


module.exports = {
  CustomError,
  DbError,
  HttpError,

  ERROR_CODE,
  STATUS,
  HTTP_STATUS,
}
